﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace DotUpdater
{
    public sealed class Utility
    {
        private const string applicationId = "1FADF880-EB85-4483-BCFC-7EE6DE8C7452";

        private Utility() {}

        public static string TempBasePath
        {
            get
            {
                string applicationTempPath =
                    Path.Combine(Path.GetTempPath(), applicationId);
//                Path.Combine(Environment.CurrentDirectory, "UAB");

                if (!Directory.Exists(applicationTempPath))
                {
                    DirectoryInfo info = Directory.CreateDirectory(applicationTempPath);
                    applicationTempPath = info.FullName;
                }
                else
                {
                    applicationTempPath = Path.GetFullPath(applicationTempPath);
                }

                return applicationTempPath;
            }
        }

        /// <summary>
        /// Extracts the files needed for waiting for a new process (which are included as embedded resources) in the 
        /// local folder.
        /// </summary>
        /// <param name="resourceName">The name of the resource to extract.</param>
        /// <param name="targetFile">The name of the file where the embedded resource will be saved.</param>
        /// <remarks>This method is a helper used to extract the two files included as embedded resources.</remarks>
        public static void ExtractResourceStream( string resourceName, string targetFile )
        {
            // Get the assembly resources
            //string[] manifestResourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
            using(Stream res = Assembly.GetExecutingAssembly().GetManifestResourceStream( resourceName ) )
            {
                if (res == null) throw new ArgumentException("Can't find resource: " + resourceName);
                using( FileStream fs = new FileStream( targetFile, FileMode.Create, FileAccess.Write ) )
                {
                    using( BinaryWriter bw = new BinaryWriter( fs ) )
                    {
                        byte[] buffer = new byte[1024];
                        int cbRead;
                        do
                        {
                            cbRead = res.Read( buffer, 0, 1024 );
                            bw.Write( buffer, 0, cbRead );
                        } while ( cbRead >= 1024 );
                    }
                }
            }
        }
    }
}
